package com.qire.common;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.bumptech.glide.Glide;
import com.qire.antsdeeplink.AntsDeepLink;
import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.lifecycleHandler.ActivityLifecycleHandler;
import com.qire.common.basic.ObjectUtil;
//import com.qire.common.constant.AdvertManage;
//import com.qire.common.model.entity.UserEntity;
//import com.qire.common.receiver.NetWorkChangReceiver;
//import com.qire.common.receiver.SimChangeReceiver;
import com.qire.common.utils.CacheStorageUtil;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.Logger;
//import com.qire.common.utils.OkGoConfigHelper;
//import com.qire.other.thirdPlatform.AliQuickLoginPlatform;
//import com.qire.other.thirdPlatform.WeChatPlatform;

import androidx.multidex.MultiDexApplication;

public class SummerApp extends MultiDexApplication {

    private static SummerApp summerApp;
    public static SummerApp summerApp() {
        return summerApp;
    }

    private int versionCode = 0;
    private String versionName = null;

    /**
     * 加载App版本号和版本名
     */
    private void loadVersionInfo() {
        try {
            PackageManager pm = getPackageManager();//拿到包的管理器
            //封装了所有的功能清单中的数据
            PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
            versionCode = info.versionCode;
            versionName = info.versionName;
            Logger.d("APP 初始化，成功加载版本号！当前appVersionCode：" + versionCode + " 当前appVersionName:" + versionName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return app应用的版本号
     */
    public int versionCode() {
        return versionCode;
    }

    /**
     * @return app应用的版本名
     */
    public String versionName() {
        return versionName;
    }

    /**
     * 获得Application里面的的meta-data的值
     * @param metaDataName {@code <meta-data android:name="" />}
     * @return
     */
    public String getMetaDataToString(String metaDataName) {
        // TODO Auto-generated method stub
        String metaDataToString = null;
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            if(ObjectUtil.nonNull(appInfo) && ObjectUtil.nonNull(appInfo.metaData)) {
                metaDataToString = appInfo.metaData.get(metaDataName).toString();
            }
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return metaDataToString;
    }


    @Override
    public void onCreate() {
        AntsRouter.init(this);
        AntsDeepLink.DISPATCHER.init(this);
        super.onCreate();
        summerApp = this;
        // 加载版本号
        loadVersionInfo();

        // 屏幕像素度量单位初始化
        EquipmentInfoUtil.init(this);

        // 初始化缓存工具，大部分需要行为需要依赖缓存，固应该优先执行初始化
        CacheStorageUtil.init(this);

//        // 用户数据本地加载缓存
//        UserEntity.self.loadLocalUserInfo();
//
//        // 初始化网络请求头，这个头还在webView中加载页面用了
//        OkGoConfigHelper.initHeader(this);
//        // okGo网络框架初始化
//        OkGoConfigHelper.initOkGo(this);

//        //定时任务队列初始化
//        TimeTaskQueue.QUEUE.init();

//
//        // MobSDK 分享
//        MobSDK.init(this);
//
//        // 全局配置初始化
////        GlobalConfig.init();
//        // 友盟统计
//        UMAnalytics.init(this);

        // 应用前后台切换监听
        registerActivityLifecycleCallbacks(new AppFrontBackStateListening());

//        // 微信平台信息初始化
//        WeChatPlatform.WeChat.init(this);
//        // 阿里手机一键登录平台初始化
//        AliQuickLoginPlatform.QUICK.init(this);
//
//        // 初始化广告相关SDK
//        AdvertManage.init(this);
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if(level == TRIM_MEMORY_UI_HIDDEN){
            Glide.get(this).clearMemory();
        }
        Glide.get(this).trimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Glide.get(this).onLowMemory();
    }

//    /** 网络状态改变监听接受器 */
//    private NetWorkChangReceiver netWorkChangReceiver;
//    /** SIM卡状态改变监听接受器 */
//    private SimChangeReceiver simChangeReceiver;

    /**
     * 添加网络监听，网络切换进行提示
     */
    private void registerReceiver() {
//        netWorkChangReceiver = new NetWorkChangReceiver(this);
//        netWorkChangReceiver.registerReceiver();
//        simChangeReceiver = new SimChangeReceiver().registerReceiver(this).addReadySimAction(() -> {
//            AliQuickLoginPlatform.QUICK.checkAccelerateLogin();
//        });
    }

    /**
     * 移除网络监听
     */
    private void unregisterReceiver() {
//        if(ObjectUtil.nonNull(netWorkChangReceiver)) {
//            netWorkChangReceiver.unregisterReceiver();
//        }
//        if(ObjectUtil.nonNull(simChangeReceiver)) {
//            simChangeReceiver.unregisterReceiver(this);
//            simChangeReceiver = null;
//        }
    }

    /**
     * Activity 生命周期监听，用于监控app前后台状态切换
     */
    public class AppFrontBackStateListening extends ActivityLifecycleHandler {
        /**
         * 当前Activity个数
         **/
        private int activityNumber = 0;

        public AppFrontBackStateListening(){}

        private void onEnteredAppForeground() {
            // App just entered the foreground. Do something here!
            registerReceiver();
        }
        private void onEnteredAppBackground() {
            // App just entered the background. Do something here!
            unregisterReceiver();
        }

        @Override
        public void onActivityStarted(Activity activity) {
            if (activityNumber == 0) {
                // app回到前台
                onEnteredAppForeground();
            }
            activityNumber++;
        }

        @Override
        public void onActivityStopped(Activity activity) {
            activityNumber--;
            if (activityNumber == 0) {
                // app回到后台
                onEnteredAppBackground();
            }
        }
    }

}